import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userApi } from '@/api/user'
import type { User, BlogConfig } from '@/types/user'

export const useUserStore = defineStore('user', () => {
  // 用户信息
  const userInfo = ref<User | null>(null)

  // 博客配置
  const blogConfig = ref<BlogConfig | null>(null)

  // token
  const token = ref<string>('')

  // 设置token
  const setToken = (newToken: string) => {
    token.value = newToken
  }

  // 清除token
  const clearToken = () => {
    token.value = ''
  }

  // 设置用户信息
  const setUserInfo = (user: User) => {
    userInfo.value = user
  }

  // 设置博客配置
  const setBlogConfig = (config: BlogConfig) => {
    blogConfig.value = config
  }

  // 登录
  const login = async (account: string, password: string) => {
    try {
      const response = await userApi.login({ account, password })
      setToken(response.token)
      // 登录成功后获取用户信息
      await fetchUserInfo()
      return response
    } catch (error) {
      throw error
    }
  }

  // 登出
  const logout = async () => {
    try {
      await userApi.logout()
    } catch (error) {
      console.error('Logout error:', error)
    } finally {
      clearToken()
      userInfo.value = null
      blogConfig.value = null
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const response = await userApi.getUserInfo()
      setUserInfo(response)
      return response
    } catch (error) {
      throw error
    }
  }

  // 获取博客配置
  const fetchBlogConfig = async () => {
    try {
      const response = await userApi.getBlogConfig()
      setBlogConfig(response)
      return response
    } catch (error) {
      throw error
    }
  }

  // 检查是否已登录
  const isLoggedIn = () => {
    return !!token.value
  }

  // 获取token（用于请求拦截器）
  const getToken = () => {
    return token.value
  }

  return {
    userInfo,
    blogConfig,
    token,
    setToken,
    clearToken,
    setUserInfo,
    setBlogConfig,
    login,
    logout,
    fetchUserInfo,
    fetchBlogConfig,
    isLoggedIn,
    getToken
  }
}, {
  persist: true
})
